<?php

namespace Modules\Entity\Library;

use Core\Forms\Form;
use Phalcon\Di;

class Entity
{
    protected $_links;
    public $id;
    public $entity;

    public function __construct($entity)
    {
        foreach ($entity as $key => $value) {
            $this->{$key} = $value;
        }
    }

    public static function toClass($entity, $data)
    {
        echo '<pre>';
        //print_r($data);
        echo '</pre>';
        foreach ($data as $key => $item) {
            $ob = new Entity($item);
            $ob->id = $key;
            $ob->entity = $entity;
            yield $ob;
        }
    }

    public static function save(Form $form)
    {
        $data = $form->getData();
        $di = Di::getDefault();
        $config = $di->getShared('config');
        $configName = 'm.'.$data['module'].'.'.ucfirst($data['entity']).'ContentModel';
        $contentModelList = $config->get($configName,[]);
        if(!$contentModelList){
            $contentModelList = [];
        }
        $contentModelList[$data['id']] = $data;
        if ($config->set($configName, $contentModelList)) {
            return $form;
        }
        return false;
    }

    /**
     * @param array $links
     * @return $this
     */
    public function setLinks(array $links)
    {
        $this->_links = $links;
        return $this;
    }

    /**
     * @return array
     */
    public function getLinks()
    {
        $this->_links = [
            'edit' => [
                'href' => [
                    'for' => 'adminEntityInfoEdit',
                    'entity' => $this->entity,
                    'contentModel' => $this->id
                ],
                'data-target' => 'right_handle',
                'icon' => 'info',
                'name' => '编辑',
            ],
        ];
        Di::getDefault()->getShared('eventsManager')->fire('entityEdit:links', $this, $this->_links);
        return $this->_links;
    }
}